picker
<template>
  <xh-container
    btnText="保存"
    @onSave="handleClickSubmit"
    :title="formData.pickPlanId ? '编辑' : '新增'"
  >
    <view class="container">
      <uni-forms
        ref="form1"
        :rules="rules1"
        :modelValue="formData"
        :label-width="80"
        label-align="right"
      >
        <uni-forms-item required label="收回时间" name="takeBackDate">
          <uni-datetime-picker
            type="date"
            v-model="formData.takeBackDate"
            :start="Date.now()"
          />
        </uni-forms-item>
        <uni-forms-item required label="产品名称" name="productName">
          <uni-data-select
            v-model="formData.productName"
            :localdata="productList"
            @change="handleChangeProduct"
          ></uni-data-select>
        </uni-forms-item>
        <uni-forms-item required label="类型" name="type">
          <uni-data-select
            v-model="formData.type"
            :localdata="typeList"
          ></uni-data-select>
        </uni-forms-item>
      </uni-forms>
      <uni-section title="新增辅料" type="line">
        <uni-table border stripe emptyText="暂无更多数据">
          <!-- 表头行 -->
          <uni-tr>
            <uni-th
              align="center"
              v-for="item in showColumns"
              :key="item.title"
              >{{ item.title }}</uni-th
            >
          </uni-tr>
          <!-- 表格数据行 -->
          <uni-tr v-for="(item, index) in tableData" :key="index">
            <uni-td align="center">{{ item.cuttingCode }}</uni-td>
            <uni-td align="center">
              {{ item.takeBackNum }}
            </uni-td>
            <template v-if="formData.type === '1'">
              <uni-td align="center">{{ item.filledShortNum }}</uni-td>
              <uni-td align="center">{{ item.changeNum }}</uni-td>
              <uni-td align="center">{{ item.cardNo }}</uni-td>
            </template>
            <uni-td align="center">{{ item.remark }}</uni-td>
            <uni-td>
              <view class="uni-group">
                <!-- <xh-button size="mini" type="primary"> 修改 </xh-button> -->
                <xh-button
                  size="mini"
                  type="warn"
                  @click="handelClickDel(index)"
                  >删除</xh-button
                >
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <xh-button :borderRadius="0" type="default" @click="handelClickAdd"
          >添加</xh-button
        >
      </uni-section>
      <xh-popup
        title="添加列表"
        ref="xhPopup"
        @ok="handleClickOk"
        @close="handleClickClose"
      >
        <uni-forms
          ref="form2"
          :modelValue="detailData"
          :label-width="90"
          :rules="rules2"
        >
          <uni-forms-item required label="裁片编码" name="cuttingCode">
            <xh-data-select
              v-model="detailData.cuttingCode"
              :localdata="cuttingList"
              @change="handleChangeCutting"
            />
          </uni-forms-item>
          <uni-forms-item label="收回片数" name="takeBackNum">
            <uni-easyinput
              type="number"
              v-model="detailData.takeBackNum"
              placeholder="请输入收回片数"
            />
          </uni-forms-item>
          <template v-if="formData.type === '1'">
            <uni-forms-item label="缺料总数" name="filledShortNum">
              <uni-easyinput
                type="digit"
                v-model="detailData.filledShortNum"
                placeholder="请输入缺料总数"
              />
            </uni-forms-item>

            <uni-forms-item label="换片总量" name="changeNum">
              <uni-easyinput
                type="digit"
                v-model="detailData.changeNum"
                placeholder="请输入换片总量"
              />
            </uni-forms-item>
            <uni-forms-item label="卡号" name="cardNo">
              <xh-data-select
                v-model="detailData.cardNo"
                :localdata="cardNoList"
              />
            </uni-forms-item>
          </template>

          <uni-forms-item label="备注" name="remark">
            <uni-easyinput
              v-model="detailData.remark"
              placeholder="请输入备注"
            />
          </uni-forms-item>
        </uni-forms>
      </xh-popup>
    </view>
  </xh-container>
</template>

<script>
import {
  getRetractionCuttingList,
  addEmbroideryRetractionRecord,
  getAccessories,
  getPersonAmountList,
  getRetractionProductList,
  getWorkOrderList,
} from "@/api/purchase/pickplanbill.js";
import { isDecimalPlaces } from "@/utils/common";
import { formatSelectList } from "@/utils/business.js";
import AppStorage from "@/utils/appStorage";
import { EmbroideryTypeEnum } from "@/utils/constant";
export default {
  // mixins: [mixins],
  data() {
    return {
      formData: {},
      detailData: {},
      tableData: [],
      productList: [],
      typeList: EmbroideryTypeEnum,
      cuttingList: [], // 裁片编码list
      pickPersonList: [],
      cardNoList: [],
      rules1: {
        takeBackDate: {
          rules: [
            {
              required: true,
              errorMessage: "请选择收回时间",
            },
          ],
        },
        productName: {
          rules: [
            {
              required: true,
              errorMessage: "请选择产品名称",
            },
          ],
        },
        cuttingList: {
          rules: [
            {
              required: true,
              errorMessage: "请选择裁片编码",
            },
          ],
        },
      },
      rules2: {
        cuttingCode: {
          rules: [
            {
              required: true,
              errorMessage: "请选择裁片！",
            },
          ],
        },
      },
    };
  },
  computed: {
    showColumns() {
      const columns = [
        {
          title: "裁片编码",
        },
        {
          title: "收回片数",
        },
        {
          title: "缺料总数",
        },
        {
          title: "换片总量",
        },
        {
          title: "卡号",
        },
        {
          title: "备注",
        },
        {
          title: "操作",
        },
      ];
      if (this.formData.type === "1") {
        return columns;
      }
      return columns.filter(
        (item) => !["缺料总数", "换片总量", "卡号"].includes(item.title)
      );
    },
  },
  created() {
    this.fetchPersonAmountList();
    this.fetchProductList();
  },
  mounted() {},
  onLoad(options) {
    const { cuttingCode, pickPlanId, ...rest } = options;
    const userInfo = AppStorage.get("userInfo");
    this.formData = {
      ...rest,
      pickPlanId,
      cuttingCode: cuttingCode?.split(","),
      pickPerson: userInfo.nickName,
    };
    this.fetchTableData(pickPlanId);
  },
  methods: {
    // 请求接口-卡号
    fetchWorkOrderList(val) {
      getWorkOrderList(val).then((res) => {
        const { rows } = res;
        this.cardNoList = formatSelectList(rows);
      });
    },
    fetchProductList() {
      getRetractionProductList().then((res) => {
        const { rows } = res;
        this.productList = formatSelectList(rows);
      });
    },
    handleChangeCutting(item) {
      const { value } = item;
      this.fetchWorkOrderList(value);
    },
    fetchPersonAmountList() {
      getPersonAmountList().then((res) => {
        const userInfo = AppStorage.get("userInfo");
        const { rows } = res;
        const person = rows.find(
          (item) => item.productName === userInfo.nickName
        );
        this.formData = {
          ...this.formData,
          totalAmount: person.totalAmount,
        };
      });
    },
    fetchTableData(id) {
      getAccessories(id).then((res) => {
        const { data } = res;
        this.tableData = data || [];
      });
    },
    handleChangeProduct(val) {
      console.log("handleChangeProduct-val", val);
    },
    fetchCuttingList() {
      const { productName } = this.formData;
      const params = {
        productName,
      };
      getRetractionCuttingList(params).then((res) => {
        const { rows } = res;
        this.cuttingList = formatSelectList(
          rows.filter((item) => item.cuttingCode),
          "cuttingCode"
        );
      });
    },
    // 关闭 添加明细弹窗
    handleClickClose() {
      this.$refs.form2.clearValidate();
      this.detailData = {};
    },
    // 删除
    handelClickDel(index) {
      this.tableData.splice(index, 1);
    },
    // 提交
    handleClickSubmit() {
      this.$refs.form1
        .validate()
        .then(() => {
          const params = {
            ...this.formData,
            list: this.tableData,
            auditStatus: "0",
          };
          addEmbroideryRetractionRecord(params).then(() => {
            this.handleSuccess();
          });
        })
        .catch((err) => {
          console.log("表单错误信息：", err);
        });
    },
    handleSuccess() {
      this.$modal.msgSuccess("操作成功！");
      this.clearData();
      this.$nav.navigateBack();
    },
    clearData() {
      this.tableData = [];
      this.detailData = {};
      this.formData = {};
    },
    // 添加明细
    handleClickOk() {
      this.$refs.form2
        .validate()
        .then(() => {
          const { changeNum, filledShortNum } = this.detailData;
          if (!isDecimalPlaces(changeNum) || !isDecimalPlaces(filledShortNum)) {
            this.$modal.msgError("保留两位小数！");
            return;
          }
          this.tableData.push(this.detailData);
          this.detailData = {};
          this.$refs.xhPopup.close();
        })
        .catch((err) => {
          console.log("表单错误信息：", err);
        });
    },
    // 添加
    handelClickAdd() {
      if (this.formData.productName) {
        this.$refs.xhPopup.open("top");
        this.fetchCuttingList();
      } else {
        this.$modal.msgError("请先选择产品名称！");
      }
    },
  },
  watch: {
    "formData.cuttingCode": {
      // immediate: true, // 如果需要在组件实例化时立即触发，设置immediate为true
      handler(newVal) {
        let pickAmount = 0;
        if (newVal) {
          pickAmount = newVal.length;
        }
        this.formData.pickAmount = pickAmount;
      },
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  padding: 10px;
}

.popup-title {
  line-height: 45px;
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  height: 45px;
  border-bottom: 1px solid #ccc;
  border-top: 1px solid #ccc;
}

.popup-footer {
  display: flex;

  button {
    flex-grow: 1;
    border-radius: 0;

    &:last-of-type {
      border-left: none;
    }
  }
}

.form-content {
  padding: 10px;
}

.btn-wrapper {
  display: flex;

  button {
    flex-grow: 1;
    border-radius: 0;

    &:last-of-type {
      border-left: none;

      &::after {
        border-left: none;
      }
    }

    &::after {
      border-radius: 0;
    }
  }
}
</style>
